const exprress = require('express')
const router = exprress.Router()
const handler = require('../RouterHandler/news')
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const storage = multer.diskStorage({
	//保存路径
	destination: function(req, file, cb) {
		let path = ['/article','/headimg','/cover_img','/crowd_img','/store_logo','/goods_details','/common']
		if (!req.body.type) {
			cb(null, "public/article")
		} else if (req.body.type == 1) {
			cb(null, "public/headimg")
		} else if (req.body.type == 2) {
			cb(null, "public/cover_img")
		} else if (req.body.type == 3) {
			cb(null, "public/crowd_img")
		} else if (req.body.type == 4) {
			cb(null, "public/store_logo")
		} else if (req.body.type == 5) {
			cb(null, "public/goods_details")
		} else if (req.body.type == 6) {
			cb(null, "public/common")
		}
		// 
		if(!req.body.oldPath) return
		req.body.oldPath = req.body.oldPath.replace(/(.*\/)*([^.]+)*/ig,"$2")
		fs.unlink(`public/${path[req.body.type || 0]}/`+req.body.oldPath, (error) => {
			if (error) throw error;
			console.log('Avatar updated successfully');
		})
		//注意这里的文件路径,不是相对路径，直接填写从项目根路径开始写就行了
	},
	//保存在 destination 中的文件名
	filename: function(req, file, cb) {
		let extname = path.extname(file.originalname)
		cb(null, Date.now() + '-' + extname)
	}
})
const upload = multer({
	storage: storage
})

//获取文章列表(不需要登录)
router.post('/common/getArticleList', handler.getArticleList)
//根据type获取
router.post('/common/getArticleListType', handler.getArticleListType)
//获取详情
router.post('/common/getArticleListId', handler.getArticleListId)
//发布文章
router.post('/user/addArticle', handler.addArticle)
//根据id删除文章
router.post('/user/delArticle', handler.delArticle)
//根据id更新文章
router.post('/user/updataArticle', handler.updataArticle)
//上传文件
router.post('/upload', upload.single('file'), handler.upload)
router.post('/uploadVideo', upload.single('file'), handler.uploadVideo)
router.post('/uploadTwo', upload.single('file'), handler.uploadTwo)
//获取文章hot榜
router.post('/user/getArticleListHot', handler.getArticleListHot)
//获取关注列表文章
router.post('/user/getFollowArticleList', handler.getFollowArticleList)
//点赞
router.post('/user/giveLike', handler.giveLike)
//根据用户获取点赞表
router.post('/user/getUserLike', handler.getUserLike)
// 评论
//根据文章id获取评论
router.post('/user/getCommentListId', handler.getCommentListId)
//根据用户id和文章id生成评论 createtime
router.post('/user/createCommentInfo', handler.createCommentInfo)
//根据用户id、文章id、评论id 删除评论
router.post('/user/delCommentListId', handler.delCommentListId)
//根据用户id获取评论
router.post('/user/getUserCommentListId', handler.getUserCommentListId)
//词条
//获取词条列表
router.post('/news/getEntryList', handler.getEntryList)
router.post('/news/createEntry', handler.createEntry)
module.exports = router